﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace GameToolkit
{
    [DisallowMultipleComponent, RequireComponent(typeof(Collider))]
    public class SubTriggerCollider : MonoBehaviour
    {
        RootTriggerCollider mRoot;
        int mSubId = -1;
        //HashSet<Collider> mColliders;

        private void Awake()
        {
            //mColliders = new HashSet<Collider>();
            OnTransformParentChanged();
        }

        private void OnDestroy()
        {
            if (mRoot != null)
            {
                mRoot.UnregistSubColliderID(mSubId);
                mRoot = null;
                mSubId = -1;
            }
        }

        private void OnTransformParentChanged()
        {
            var parent = transform.parent;
            var root = parent == null ? null : parent.GetComponentInParent<RootTriggerCollider>();
            if (root != mRoot)
            {
                //foreach(var collider in mColliders)
                //{
                //    if (mRoot != null)
                //        mRoot.UnregistCollider(collider);
                //    if (root != null)
                //        root.RegistCollider(collider);
                //}
                if (mRoot != null)
                    mRoot.UnregistSubColliderID(mSubId);
                mSubId = root == null ? -1 : root.RegistSubColliderID(this);
                mRoot = mSubId == -1 ? null : root;
            }
        }

        private void OnTriggerEnter(Collider other)
        {
            if (mRoot != null)
            {
                mRoot.RegistCollider(mSubId, other);
            }
        }

        private void OnTriggerExit(Collider other)
        {
            if (mRoot != null)
            {
                mRoot.UnregistCollider(mSubId, other);
            }
        }

#if UNITY_EDITOR
        private void OnValidate()
        {
            var col = GetComponent<Collider>();
            if (col != null)
                col.isTrigger = true;
        }
#endif
    }
}
